package copyengine.utils.objectpool.unuse
{
	public class ObjectPool
	{
		private var commonObjectFactory:CommonObjectFactory;
		private var factoryPool:Vector.<IObjectFactory>;
		
		private static var _instance:ObjectPool;
		
		public static function get instance():ObjectPool
		{
			if (_instance == null)
			{
				_instance = new ObjectPool();
			}
			return _instance;
		}
		
		public function ObjectPool()
		{
			this.factoryPool = new Vector.<IObjectFactory>;
			this.commonObjectFactory = new CommonObjectFactory(500);
		}
		
		public function registerFactory(_objectFactory:IObjectFactory):void
		{
			if (!this.findFactory(_objectFactory))
			{
				this.factoryPool.push(_objectFactory);
			}
		}
		
		public function unregisterFactory(_objectFactory:IObjectFactory):void
		{
			if (this.findFactory(_objectFactory))
			{
				var len:int = this.factoryPool.length;
				
				for (var i:int = 0; i < len; i++)
				{
					if (this.factoryPool[i] == _objectFactory)
					{
						this.factoryPool.splice(i, 1);
						break;
					}
				}
			}
		}
		
		public function findFactory(_objectFactory:IObjectFactory):Boolean
		{
			var len:int = this.factoryPool.length;
			
			for (var i:int = 0; i < len; i++)
			{
				if (this.factoryPool[i] == _objectFactory)
				{
					return true;
				}
			}
			
			return false;
		}
		
		public function createObject(_uniqueName:String):IPoolObject
		{
			var poolObject:IPoolObject = null;;
			var len:int = this.factoryPool.length;
			
			for (var i:int = 0; i < len; i++)
			{
				poolObject = this.factoryPool[i].createObject(_uniqueName);
				if (poolObject)
				{
					return poolObject;
				}
			}
			
			return poolObject;
		}
		
		public function recycleObject(_uniqueName:String, _object:IPoolObject):void
		{
			var len:int = this.factoryPool.length;
			
			for (var i:int = 0; i < len; i++)
			{
				if (this.factoryPool[i].nameIsExist(_uniqueName))
				{
					this.factoryPool[i].recycleObject(_uniqueName, _object);
				}
			}
		}
		
		public function dispose():void
		{
			var len:int = this.factoryPool.length;
			
			for (var i:int = 0; i < len; i++)
			{
				this.factoryPool[i].disposeFactory();
			}
			
			this.factoryPool = null;
			
			this.commonObjectFactory.disposeFactory();
			this.commonObjectFactory = null;
		}
		
		public function createCommonObject(_uniqueName:String):Object
		{
			if (this.commonObjectFactory)
			{
				return this.commonObjectFactory.createObjectOfData(_uniqueName);
			}
			return null;
		}
		
		public function recycleCommonObject(_uniqueName:String, _object:Object):void
		{
			if (this.commonObjectFactory)
			{
				return this.commonObjectFactory.recycleObjectOfData(_uniqueName, _object);
			}
		}
	}
}